package com.nw.controller;

import com.nw.service.MongoService;
import com.nw.utils.RequestUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("mongo")
public class MongoController {
    @Autowired
    MongoService mongoService;

    @RequestMapping("queryCount")
    @ResponseBody
    private long queryCount(String tableName, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        return mongoService.queryCount(tableName,query);
    }
    @RequestMapping("query")
    @ResponseBody
    private List<Document> query(String tableName,Integer skip,Integer limit, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        return mongoService.query(tableName,query,null,skip!=null?skip:0,limit!=null?limit:0);
    }
    @RequestMapping("queryFields")
    @ResponseBody
    private List<Document> queryFields(String tableName, Integer skip,Integer limit,HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        return mongoService.queryFields(tableName,query,null,skip!=null?skip:0,limit!=null?limit:0);
    }
    @RequestMapping("queryOne")
    @ResponseBody
    private Document queryOne(String tableName, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        return mongoService.queryOne(tableName,query);
    }

    @RequestMapping("add")
    @ResponseBody
    private long add(String tableName, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        mongoService.add(tableName,query);
        return 1;
    }
    @RequestMapping("delete")
    @ResponseBody
    private long delete(String tableName, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        mongoService.delete(tableName,query);
        return 1;
    }
    @RequestMapping("update")
    @ResponseBody
    private long update(String tableName, HttpServletRequest request){
        Map<String, Object> query = RequestUtil.getQuery(request);
        Map<String, Object> update = new HashMap<>();
        update.put("_id",query.get("_id"));
        mongoService.update(tableName,update,query);
        return 1;
    }

}
